package com.yuanduan.mplus.view;


import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cj.framework.app.BaseActivity;
import com.cj.framework.util.HttpImp;
import com.cj.framework.util.IHttp;
import com.cj.framework.util.RSAUtils;
import com.google.gson.Gson;
import com.yuanduan.mplus.R;
import com.yuanduan.mplus.config.Config;
import com.yuanduan.mplus.model.DBManager;
import com.yuanduan.mplus.model.entity.RS;
import com.yuanduan.mplus.model.entity.User;
import com.yuanduan.mplus.util.FileImageUpload;

import java.io.File;
import java.util.HashMap;


public class OwnerInsureActivity extends BaseActivity implements View.OnClickListener {
    private static final  int CAPTURE_IMAGE=10;
    private static final int GALLERY_IMAGE=11;
    private ImageView iv_front;
    private ImageView iv_back;
    private EditText et_identityNum;
    private TextView tv_submit;
    private ImageButton ib_back;

    private String identityNum;
    private Bitmap backPic;
    private Bitmap frontPic;
    private Dialog dialog;
    private int status=0;
    private String mCurrentPath;
    private String path1;
    private String path2;
    private ProgressDialog progressDialog;

    private IHttp iHttp=new HttpImp();
    private IHttp.HttpInfoCallback callback=new IHttp.HttpInfoCallback() {
        @Override
        public void onSucceed(Object result) {
            RS rs= (RS) Config.decry(result,RS.class);
            if(rs.getRs()==1){
                Toast.makeText(OwnerInsureActivity.this,"身份证号码上传完成",Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(OwnerInsureActivity.this,"身份证号码上传失败",Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailed(Exception e) {
            Toast.makeText(OwnerInsureActivity.this,"身份证号码上传失败.",Toast.LENGTH_SHORT).show();
        }
    };

    @Override
    protected void findId() {
        ib_back= (ImageButton) findViewById(R.id.ownerinsure_ib_back);
        tv_submit= (TextView) findViewById(R.id.ownerinsure_tv_submit);
        et_identityNum= (EditText) findViewById(R.id.ownerinsure_et_identityNum);
        iv_back= (ImageView) findViewById(R.id.ownerinsure_iv_identityBack);
        iv_front= (ImageView) findViewById(R.id.ownerinsure_iv_identityFront);
    }

    @Override
    protected void logic() {
        ib_back.setOnClickListener(this);
        tv_submit.setOnClickListener(this);
        iv_front.setOnClickListener(this);
        iv_back.setOnClickListener(this);

        progressDialog=new ProgressDialog(this);
        dialog=new Dialog(this);
        dialog.setContentView(R.layout.ownerinsure_dialog);
        View gallery=dialog.findViewById(R.id.ownerinsure_tv_gallery);
        View camera=dialog.findViewById(R.id.ownerinsure_tv_camera);
        gallery.setOnClickListener(this);
        camera.setOnClickListener(this);
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_owner_insure;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ownerinsure_ib_back:
                this.finish();
                break;
            case R.id.ownerinsure_tv_submit:
                identityNum=et_identityNum.getText().toString().trim();
                if(TextUtils.isEmpty(identityNum)){
                    return;
                }
                HashMap<String,String> hashMap=new HashMap<>();
                final User user= DBManager.getInstance(this).getUser();
                hashMap.put("UserPhone",user.getUserPhone());
                hashMap.put("UserPassword",user.getUserPwd());
                hashMap.put("IDCard",identityNum);
                iHttp.httpInfoPost(Config.URL+Config.UPDATE_IDCARD,Config.translateMap(hashMap),callback);

                //上传身份证照片
                if(TextUtils.isEmpty(path1)||TextUtils.isEmpty(path2)){
                    return;
                }

                //正面
                new Thread(){
                    @Override
                    public void run() {
                        HashMap<String,String> map=new HashMap<String, String>();
                        map.put("UserPhone",RSAUtils.encryptWithRSA(user.getUserPhone()));
                        map.put("UserPassword",RSAUtils.encryptWithRSA(user.getUserPwd()));
                        map.put("ZF",RSAUtils.encryptWithRSA("z"));
//                        String result=FileImageUpload.uploadFile(new File(path1),"File",map,Config.URL+Config.UPDATE_IDCARDIMAGE);
//                        Log.d("xx","result zm:"+result);
//                        if(result.equals("1")){
//                            Toast.makeText(OwnerInsureActivity.this,"正面照片上传成功",Toast.LENGTH_SHORT).show();
//                        }else{
//                            Toast.makeText(OwnerInsureActivity.this,"正面照片上传失败",Toast.LENGTH_SHORT).show();
//                        }
                    }
                }.start();
                //反面
                new Thread(){
                    @Override
                    public void run() {
                        HashMap<String,String> map=new HashMap<String, String>();
                        map.put("UserPhone",RSAUtils.encryptWithRSA(user.getUserPhone()));
                        map.put("UserPassword",RSAUtils.encryptWithRSA(user.getUserPwd()));
                        map.put("ZF",RSAUtils.encryptWithRSA("f"));
//                        String result=FileImageUpload.uploadFile(new File(path2),"File",map,Config.URL+Config.UPDATE_IDCARDIMAGE);
//                        Log.d("xx","result fm:"+result);
//                        if(result.equals("1")){
                            Toast.makeText(OwnerInsureActivity.this,"反面照片上传成功",Toast.LENGTH_SHORT).show();
//                        }else{
                            Toast.makeText(OwnerInsureActivity.this,"反面照片上传失败",Toast.LENGTH_SHORT).show();
//                        }
                    }
                }.start();
                HashMap<String,String> hashMap1=new HashMap<>();
                hashMap1.put("UserPhone",user.getUserPhone());
                hashMap1.put("UserPassword",user.getUserPwd());
                iHttp.httpInfoPost(Config.URL+Config.APPLYIDCARD, Config.translateMap(hashMap1), new IHttp.HttpInfoCallback() {
                    @Override
                    public void onSucceed(Object result) {
                        RS rs= (RS) Config.decry(result,RS.class);
                        if(rs.getRs()==1){
                            Toast.makeText(OwnerInsureActivity.this,"申请成功",Toast.LENGTH_SHORT).show();
                        }else{
                            Toast.makeText(OwnerInsureActivity.this,"申请失败",Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailed(Exception e) {
                        Toast.makeText(OwnerInsureActivity.this,"申请失败1",Toast.LENGTH_SHORT).show();
                    }
                });
                break;
            case R.id.ownerinsure_iv_identityFront:
                status=1;
                dialog.show();
                break;
            case R.id.ownerinsure_iv_identityBack:
                status=2;
                dialog.show();
                break;
            case R.id.ownerinsure_tv_camera:
                openCapture();
                break;
            case R.id.ownerinsure_tv_gallery:
                selectImage();
                break;
        }
    }

    private void selectImage() {
        Intent intent=new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        if(intent.resolveActivity(getPackageManager())!=null){
            startActivityForResult(intent,GALLERY_IMAGE);
        }else{
            Toast.makeText(this,"未找到图片查看器",Toast.LENGTH_SHORT).show();
        }
    }

    private void openCapture() {
        Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if(intent.resolveActivity(getPackageManager())!=null){
            File file=createFile();
            if(file!=null){
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
                startActivityForResult(intent,CAPTURE_IMAGE);
            }
        }else{
            Toast.makeText(this,"无法启动相机",Toast.LENGTH_SHORT).show();
        }
    }

    private File createFile() {
        File file=null;
        if(status==1){
            file=new File(getExternalCacheDir(),"front.jpeg");
        }else if(status==2){
            file=new File(getExternalCacheDir(),"back.jpeg");
        }
        mCurrentPath=file.getAbsolutePath();
        if(file.exists()){
            file.delete();
        }
        return file;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        dialog.dismiss();
        if(resultCode==RESULT_OK){
            String filePath=null;
            if(requestCode==CAPTURE_IMAGE){
                if (mCurrentPath!=null)
                    filePath=mCurrentPath;
            }else if(requestCode==GALLERY_IMAGE){
                filePath=getFilePathFromContentUri(data.getData());
            }
            if(!TextUtils.isEmpty(filePath)){
                Bitmap bitmap= BitmapFactory.decodeFile(filePath);
                if(status==1){
                    path1=filePath;
                    frontPic=bitmap;
                    iv_front.setImageBitmap(frontPic);
                }else if(status==2){
                    path2=filePath;
                    backPic=bitmap;
                    iv_back.setImageBitmap(backPic);
                }
            }
        }
    }

    private String getFilePathFromContentUri(Uri data) {
        String result="";
        String[] filePathColumn={MediaStore.MediaColumns.DATA};
        Cursor cursor=this.getContentResolver().query(data,filePathColumn,null,null,null);
        if(cursor==null){
            return null;
        }
        cursor.moveToFirst();
        result=cursor.getString(cursor.getColumnIndex(filePathColumn[0]));
        cursor.close();
        return result;
    }
}
